import 'package:lib_common/lib_common.dart';
import 'package:lib_http/lib_http.dart';

class HttpConfigPage extends StatefulWidget {
  const HttpConfigPage({super.key});

  @override
  State<HttpConfigPage> createState() => _HttpConfigPageState();
}

class _HttpConfigPageState extends State<HttpConfigPage> {
  TextEditingController? urlController;

  Map<String, dynamic> headers = {};

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
            leading: GestureDetector(
                child:
                    Container(width: kToolbarHeight, color: Colors.transparent, child: const Icon(Icons.arrow_back, color: Colors.black87)),
                onTap: () => Navigator.pop(context)),
            backgroundColor: Colors.white,
            elevation: 1.0,
            actions: [_buildSaveAction(context)],
            shadowColor: Colors.black26,
            centerTitle: true,
            title: const Text("Request Config", style: TextStyle(color: Colors.black87, fontSize: 18.0, fontWeight: FontWeight.w500))),
        body: ListView(children: [
          _buildBaseUrl(),
          Container(
              height: 40.0,
              alignment: Alignment.centerLeft,
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: const Text("Common Headers", style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.w500))),
          _buildCommonHeader()
        ]));
  }

  Widget _buildSaveAction(BuildContext context) {
    return GestureDetector(
        child: Container(
            width: kToolbarHeight,
            color: Colors.transparent,
            alignment: Alignment.center,
            child: const Text("Save", style: TextStyle(color: Colors.blue))),
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
          _saveConfig(context);
        });
  }

  Widget _buildBaseUrl() {
    return Container(
        height: 48.0,
        margin: const EdgeInsets.symmetric(vertical: 6.0, horizontal: 8.0),
        decoration: BoxDecoration(color: Colors.black.withOpacity(0.05), borderRadius: BorderRadius.circular(4.0)),
        child: Row(children: [
          Container(
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: const Text("BASE URL", style: TextStyle(fontWeight: FontWeight.bold))),
          Container(width: 1.0, height: 20.0, color: Colors.black12),
          Expanded(
              child: TextField(
                  controller: urlController,
                  decoration: const InputDecoration(
                      hintText: "请输入url", border: InputBorder.none, contentPadding: EdgeInsets.symmetric(horizontal: 10.0))))
        ]));
  }

  Widget _buildCommonHeader() {
    List<Widget> children = [];
    children.add(Container(
        height: 40.0,
        margin: const EdgeInsets.symmetric(horizontal: 8.0),
        decoration: BoxDecoration(
            color: Colors.black.withOpacity(0.05),
            borderRadius: const BorderRadius.only(topLeft: Radius.circular(4.0), topRight: Radius.circular(4.0))),
        child: Row(children: [
          const Expanded(child: Text("Key", textAlign: TextAlign.center, style: TextStyle(fontWeight: FontWeight.bold))),
          Container(width: 1.0, height: 20.0, color: Colors.black12),
          const Expanded(child: Text("Value", textAlign: TextAlign.center, style: TextStyle(fontWeight: FontWeight.bold)))
        ])));
    for (var element in headers.keys) {
      children.add(Container(
          height: 40.0,
          margin: const EdgeInsets.symmetric(horizontal: 8.0),
          decoration: BoxDecoration(border: Border.all(color: Colors.black.withOpacity(0.05))),
          child: Row(children: [
            Expanded(child: Text(element, textAlign: TextAlign.center, style: const TextStyle(fontWeight: FontWeight.bold))),
            Container(width: 0.5, color: Colors.black12),
            Expanded(child: Text("${headers[element]}", textAlign: TextAlign.center, style: const TextStyle(fontWeight: FontWeight.bold)))
          ])));
    }
    return Column(children: children);
  }

  void _saveConfig(BuildContext context) {
    String? url = urlController?.text;
    if (url == null || url.isEmpty) {
      SmartDialog.showToast("请输入url");
      return;
    }
    HttpManager.getInstance().updateBaseUrl(url);
    Navigator.pop(context);
  }

  @override
  void initState() {
    super.initState();
    urlController = TextEditingController();
    urlController!.text = HttpManager.getInstance().client.options.baseUrl;

    List<HeaderInterceptor> interceptors = HttpManager.getInstance().client.interceptors.whereType<HeaderInterceptor>().toList();
    for (HeaderInterceptor interceptor in interceptors) {
      headers.addAll(interceptor.commonHeader);
    }
  }

  @override
  void dispose() {
    super.dispose();
    urlController?.dispose();
  }
}
